package com.apes.hr.base.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.hr.base.model.Employee;
import com.apes.hr.base.model.TransferRecord;
import com.apes.hr.base.repository.EmployeeRepository;
import com.apes.hr.base.repository.TransferRecordRepository;
import com.apes.hr.recruit.model.ApplyJobOrder;
import com.apes.hr.recruit.repository.ApplyJobOrderRepository;
import com.apes.hr.transfer.model.TransferApplication;
import com.apes.hr.transfer.model.TransferApplicationItem;
import com.apes.hr.transfer.repository.TransferApplicationItemRepository;
import com.apes.hr.transfer.repository.TransferApplicationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能：调动记录
 *
 * @author linwz
 * @create 2019-03-01 10:35
 */
@Service("transferRecordService")
public class TransferRecordService extends DomainService {

   @Autowired
   TransferRecordRepository transferRecordRepository;

   @Autowired
   TransferApplicationRepository transferApplicationRepository;

   @Autowired
   TransferApplicationItemRepository transferApplicationItemRepository;

   @Autowired
   EmployeeRepository employeeRepository;
   @Autowired
   SequenceService sequenceService;
   @Autowired
    ApplyJobOrderRepository applyJobOrderRepository;


   //为个人有多个调动记录写入调离时间
   public void initTransferRecord(SimpleRequest request){
       List<TransferRecord> transferRecordList = transferRecordRepository.findAll();
       Map<Employee,List<TransferRecord>> empTransferList = transferRecordList.stream().collect(Collectors.groupingBy(TransferRecord::getEmployee));
       for (Map.Entry<Employee, List<TransferRecord>> entry : empTransferList.entrySet()){
           List<TransferRecord> transferRecords = entry.getValue();
           List<TransferRecord> newtransferRecords = transferRecords.stream().sorted(Comparator.comparing(TransferRecord::getTransferOn)).collect(Collectors.toList());//根据调入时间自然顺序
           for (int i = 1; i<newtransferRecords.size();i++){
              TransferRecord transferRecord = newtransferRecords.get(i-1);//获取前一个
              if (i<newtransferRecords.size()){
                  Date date = newtransferRecords.get(i).getTransferOn();
                  transferRecord.setTransferOut(dateAdd(date,-1));
              }

           }
       }

   }

    /**
     * 获取全部调动单按个人与时间进行分组
     */
   public void getTransferApplication(SimpleRequest request){
      
       List<TransferApplication> transferApplicationList =transferApplicationRepository.findAll().stream().filter(transferApplication -> transferApplication.getHrTransferType().getId().equals("000102")).collect(Collectors.toList());
       List<TransferApplicationItem> transferApplicationItemList = transferApplicationItemRepository.findAll().stream().filter(item -> item.getTransferApplications().getHrTransferType().getId().equals("000102")
               && item.isIconExecute() && !item.isRepeal()).collect(Collectors.toList());
       //分组
       Map<Employee,List<TransferApplicationItem>> empTransferList = transferApplicationItemList.stream().collect(Collectors.groupingBy(TransferApplicationItem::getTransferUid));

       List<TransferRecord> transferRecordList = new ArrayList<>();
       for (Map.Entry<Employee, List<TransferApplicationItem>> entry : empTransferList.entrySet()){
           List<TransferApplicationItem> TransferApplicationItems = entry.getValue();
           Employee employee = entry.getKey();
           List<TransferApplicationItem> newtransferRecords = TransferApplicationItems.stream().sorted(Comparator.comparing(TransferApplicationItem::getEffectiveDate)).collect(Collectors.toList());//根据调入时间自然顺序

           for (int i = 1; i<newtransferRecords.size();i++) {
               TransferRecord transferRecord= new TransferRecord();
               TransferRecord transferRecord2;//剩下的调动记录
               TransferApplicationItem transferApplicationItem = newtransferRecords.get(i - 1);//获取调动单
               //设置前一张单的调离时间
               transferRecord2 = transferRecordRepository.findByEmployee(employee).get(0);//因为之前清理了，而且新增了一条
               transferRecord2.setTransferOut(dateAdd(transferApplicationItem.getEffectiveDate(),-1));
               transferRecordRepository.save(transferRecord2);
               //设置最新一张调动记录
//               String code = sequenceService.getId("hr_Transfer_Record" );//获取序列
//               transferRecord.setId(Long.valueOf(code));
               transferRecord.setEmployee(employee);
               transferRecord.setTransferApplicationItemId(String.valueOf(transferApplicationItem.getId()));
               transferRecord.setWorkBranch(transferApplicationItem.getBranch());
               transferRecord.setPost(transferApplicationItem.getWorkPost());
               transferRecord.setJob(transferApplicationItem.getJob());
               transferRecord.setRank(transferApplicationItem.getRankId());
               transferRecord.setOnDutyState(transferApplicationItem.getOnDutyState());
               transferRecord.setDriver(transferApplicationItem.isDriver());
               transferRecord.setEchelon(transferApplicationItem.isEchelon());
               transferRecord.setValid(true);
               transferRecord.setTransferOn(employee.getEntryDate());
               transferRecord.setTransferOut(dateAdd(transferApplicationItem.getEffectiveDate(),-1));
               transferRecordList.add(transferRecord);
           }
       }
       transferRecordRepository.save(transferRecordList);
   }
    /**
     * 传入的时间加一天
     * @param date
     * @return
     */
    private Date dateAdd(Date date,int i){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, i);//+1今天的时间加一天
        return calendar.getTime();
    }

    /**
     * 给每个人添加初始调动记录
     * @param request
     */
    public void addTransferRecord(SimpleRequest request){
        //清空调动记录单
        transferRecordRepository.deleteAll();
        //为每个人添加一条调动记录
        List<Employee> employeeList = employeeRepository.findAll().stream().filter(employee -> employee.getState()!="delete").collect(Collectors.toList());
        List<TransferRecord> transferRecordByEmpList = new ArrayList<>();
        employeeList.stream().forEach(employee -> {
            TransferRecord transferRecord = new TransferRecord();//第一条调动记录
            //设置第一张调动记录
//           String code = sequenceService.getId("hr_Transfer_Record" );//获取序列
//           transferRecord.setId(Long.valueOf(code));
            List<ApplyJobOrder> applyJobOrderList = applyJobOrderRepository.findByEmployee(employee).stream().filter(applyJobOrder -> applyJobOrder.getState().equals("done")).sorted(Comparator.comparing(ApplyJobOrder::getAgreeEntryDate)).collect(Collectors.toList());
            if (!applyJobOrderList.isEmpty())transferRecord.setApplyJobOrderId(selectLastOne(applyJobOrderList).getId());
            transferRecord.setEmployee(employee);
            transferRecord.setWorkBranch(employee.getWorkBranch());
            transferRecord.setPost(employee.getPost());
            transferRecord.setJob(employee.getJob());
            transferRecord.setRank(employee.getRank());
            transferRecord.setOnDutyState(employee.getOnDutyState());
            transferRecord.setDriver(employee.isDriver());
            transferRecord.setEchelon(employee.isEchelon());
            transferRecord.setValid(true);
            transferRecord.setTransferOn(employee.getEntryDate());
            transferRecordByEmpList.add(transferRecord);
        });
        fun1(transferRecordByEmpList);
//        transferRecordRepository.save(transferRecordByEmpList);
    }


    /**
     * 当有调动单时写入记录
     * @param request
     */
    public void setTransferRecord(SimpleRequest request){

        List<TransferRecord> transferRecords = new ArrayList<>();
        //调动明细单
        List<TransferApplicationItem> transferApplicationItemList = transferApplicationItemRepository.findAll().stream().filter(item -> item.getTransferApplications().getHrTransferType().getId().equals("000102")
                && item.isIconExecute() && !item.isRepeal() && item.getTransferUid().getEmployeeState().getId().equals("000088") && item.getTransferUid().getState()!="delete").collect(Collectors.toList());
        //分组
        Map<Employee,List<TransferApplicationItem>> empTransferList = transferApplicationItemList.stream().collect(Collectors.groupingBy(TransferApplicationItem::getTransferUid));
        for (Map.Entry<Employee, List<TransferApplicationItem>> entry : empTransferList.entrySet()){
            List<TransferApplicationItem> TransferApplicationItems = entry.getValue();
            Employee employee = entry.getKey();
            List<TransferApplicationItem> newtransferRecords = TransferApplicationItems.stream().sorted(Comparator.comparing(TransferApplicationItem::getEffectiveDate)).collect(Collectors.toList());//根据调入时间自然顺序
            TransferRecord transferRecord2 = new TransferRecord();//前一张调动单
            for (int i = 1; i<=newtransferRecords.size();i++) {
                TransferRecord transferRecord= new TransferRecord();
                TransferApplicationItem transferApplicationItem = newtransferRecords.get(i - 1);//获取调动单
                if(i == 1 ) {
                    if(!employee.getState().equals("delete")){
                        //设置前一张单的调离时间
                        transferRecord2 = transferRecordRepository.findByEmployee(employee).get(0);//因为之前清理了，而且新增了一条
                        //如果没入职单号，用第一张调动的调前部门，岗位，职位，职级，在职状态，是否准驾人员，是否梯队
                        if(transferRecord2.getApplyJobOrderId()==null){
                            transferRecord2.setWorkBranch(transferApplicationItem.getBranch());
                            transferRecord2.setPost(transferApplicationItem.getWorkPost());
                            transferRecord2.setJob(transferApplicationItem.getJob());
                            transferRecord2.setRank(transferApplicationItem.getRankId());
                            transferRecord2.setOnDutyState(transferApplicationItem.getOnDutyState());
                            transferRecord2.setDriver(transferApplicationItem.isDriver());
                            transferRecord2.setEchelon(transferApplicationItem.isEchelon());
                        }
                        transferRecord2.setTransferOut(dateAdd(transferApplicationItem.getEffectiveDate(),-1));
                        transferRecordRepository.save(transferRecord2);
                    }

                } else if (i<=newtransferRecords.size()){
                    transferRecord2.setTransferOut(dateAdd(transferApplicationItem.getEffectiveDate(),-1));
                    transferRecordRepository.save(transferRecord2);
                }
                //设置最新一张调动记录
//              String code = sequenceService.getId("hr_Transfer_Record" );//获取序列
//               transferRecord.setId(Long.valueOf(code));
                transferRecord.setEmployee(employee);
                transferRecord.setTransferApplicationItemId(String.valueOf(transferApplicationItem.getId()));
                transferRecord.setOldTransferApplicationItemId(transferRecord2.getTransferApplicationItemId());
                transferRecord.setWorkBranch(transferApplicationItem.getBranchAfter());
                transferRecord.setPost(transferApplicationItem.getWorkPostAfter());
                transferRecord.setJob(transferApplicationItem.getJobAfter());
                transferRecord.setRank(transferApplicationItem.getRankIdAfter());
                transferRecord.setOnDutyState(transferApplicationItem.getOnDutyStateAfter());
                transferRecord.setDriver(transferApplicationItem.isDriver());
                transferRecord.setEchelon(transferApplicationItem.isEchelon());
                transferRecord.setValid(true);
                transferRecord.setTransferOn(transferApplicationItem.getEffectiveDate());
//                transferRecord.setTransferOut(dateAdd(transferApplicationItem.getEffectiveDate(),-1));
                transferRecords.add(transferRecord);
                transferRecord2 = transferRecord;
                }
            }
        fun1(transferRecords);
        }


    /**
     * 批量插入
     */
    public void fun1(List<TransferRecord> originData) {

        //批量存储的集合
        List<TransferRecord> data = new ArrayList<>();

        //批量存储
        for(TransferRecord student : originData) {
            if(data.size() == 100) {
                transferRecordRepository.save(data);
                data.clear();
            }
            data.add(student);
        }

        if(!data.isEmpty()) {
            transferRecordRepository.save(data);
        }

    }

    public ApplyJobOrder selectLastOne(List<ApplyJobOrder> list) {
        ApplyJobOrder card = list.get(0);

        Long dates[] = new Long[list.size()];
        for (int i = 1; i <= list.size(); i++) {
            // 把date类型的时间对象转换为long类型，时间越往后，long的值就越大，
            // 所以就依靠这个原理来判断距离现在最近的时间
            dates[i-1] = list.get(i-1).getAgreeEntryDate().getTime();
        }
        Long maxIndex = dates[0];// 定义最大值为该数组的第一个数
        for (int j = 0; j < dates.length; j++) {
            if (maxIndex < dates[j]) {
                maxIndex = dates[j];
                // 找到了这个j
                card = list.get(j);
            }
        }
        return card;
    }


}
